from django.http import HttpResponse, JsonResponse, Http404
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import status, mixins,generics
from rest_framework.decorators import api_view
from rest_framework.views import APIView
from rest_framework.response import Response

'''
使用mixins类来简化代码编写
'''
class SnippetList(mixins.ListModelMixin,
                  mixins.CreateModelMixin,
                  generics.GenericAPIView):
    
    # 获取所有对象的方式
    queryset=Snippet.objects.all()
    
    # 提供类型的解析方式，这样CreateModelMixin类就能够知道创建对象是怎么样从参数解析出对象
    serializer_class = SnippetSerializer

    """
    List all code snippets, or create a new snippet.
    """
    def get(self,request, *args, **kwargs):
        # 返回queryset中的所有对象
        return self.list(request, *args, **kwargs)

    def post(self, request,*args, **kwargs):
        return self.create(request,*args, **kwargs)
    
class SnippetDetail(mixins.RetrieveModelMixin,
                    mixins.UpdateModelMixin,
                    mixins.DestroyModelMixin,
                    generics.GenericAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer
    
    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)